import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';

class RemoteStreamView extends StatefulWidget {
  final StreamController<int>? controller;
  const RemoteStreamView({Key? key,this.controller}) : super(key: key);

  @override
  _RemoteStreamViewState createState() => _RemoteStreamViewState();
}

class _RemoteStreamViewState extends State<RemoteStreamView> {
  final _remoteRenderer = RTCVideoRenderer();
  RTCPeerConnection? _peerConnection;

  String get sdpSemantics => 'unified-plan';

  @override
  void initState() {
    super.initState();
    widget.controller!.stream.listen((event) {
      _makeCall();
    });
    initRenderers();
  }

  @override
  void dispose() {
    _remoteRenderer.srcObject = null;
    _remoteRenderer.dispose();
    super.dispose();
  }

  ///初始化
  void initRenderers() async {
    await _remoteRenderer.initialize();
  }

  ///开始创建连接
  _makeCall() async {
    final mediaConstraints = <String, dynamic>{
      'audio': false,
      'video': {
        'mandatory': {
          'minWidth':
          '640', // Provide your own width, height and frame rate here
          'minHeight': '480',
          'minFrameRate': '30',
        },
        'facingMode': 'user',
        'optional': [],
      }
    };

    String _url = "wss://8.141.171.155:80";
    String _oUrl = "stun:stun.l.google.com:19302";
    var configuration = <String, dynamic>{
      'iceServers': [
        {'url': _oUrl},
      ],
      'sdpSemantics': sdpSemantics
    };

    final offerSdpConstraints = <String, dynamic>{
      'mandatory': {
        'OfferToReceiveAudio': true,
        'OfferToReceiveVideo': true,
      },
      'optional': [],
    };
    final loopbackConstraints = <String, dynamic>{
      'mandatory': {},
      'optional': [
        {'DtlsSrtpKeyAgreement': false},
      ],
    };

    if (_peerConnection != null) return;
    try{
      _peerConnection = await createPeerConnection(configuration, loopbackConstraints);
      _peerConnection!.onTrack = _onTrack;
      _peerConnection!.onAddTrack = _onAddTrack;
      _peerConnection!.onRemoveTrack = _onRemoveTrack;
      var description = await _peerConnection!.createOffer(offerSdpConstraints);
      await _peerConnection!.setLocalDescription(description);
      description.type = 'answer';
      await _peerConnection!.setRemoteDescription(description);
      print("state===>${_peerConnection?.connectionState}");
    }catch(e){
      print("$e");
    }
  }


  void _onTrack(RTCTrackEvent event) {
    print('onTrack');
    if (event.track.kind == 'video') {
      _remoteRenderer.srcObject = event.streams[0];
    }
  }

  void _onAddTrack(MediaStream stream, MediaStreamTrack track) {
    if (track.kind == 'video') {
      _remoteRenderer.srcObject = stream;
    }
  }

  void _onRemoveTrack(MediaStream stream, MediaStreamTrack track) {
    if (track.kind == 'video') {
      _remoteRenderer.srcObject = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: OrientationBuilder(
        builder: (context, orientation) {
          return Center(
            child: Container(
              margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              // width: MediaQuery.of(context).size.width,
              // height: MediaQuery.of(context).size.height,
              width: 80,
              height: 120,
              decoration: BoxDecoration(color: Colors.black54),
              child: RTCVideoView(
                _remoteRenderer,
                mirror: false,
                objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
                filterQuality: FilterQuality.medium,
              ),
            ),
          );
        },
      ),
    );
  }
}
